package com.pug.service;

import com.pug.feign.OrderServiceFeign;
import com.pug.feign.ProductServiceFeign;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022-07-06$ 19:54$
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessService {

    private final ProductServiceFeign productServiceFeign;
    private final OrderServiceFeign orderServiceFeign;

    // 分布式事务的设置点 TM
    @GlobalTransactional
    public void purchase(Long userId, Long productId, Integer count) {
        // 远程调用产品服务 - 扣减库存 global lock-----T1------local lock----commit
        boolean flag1 = productServiceFeign.deduct(productId, count);
        // 注意：一定要考虑fegin调用过程中出错的 兜底方案(兜底的也要考虑进去)
        if (!flag1) {
            throw new RuntimeException("产品-库存不足，执行回滚 ...");
        }

        // 远程调用订单服务 - 开始下单 ----> 订单服务调用----(生成订单)----> 用户服务(扣减库存)
        boolean flag2 = orderServiceFeign.createOrder(userId, productId, count);
        // 注意：一定要考虑fegin调用过程中出错的 兜底方案(兜底的也要考虑进去)
        if (!flag2) {
            throw new RuntimeException("用户-余额不足，执行回滚 ...");
        }
    }
}
